﻿using System;
using System.Reflection;

namespace Utils
{
    /// <summary>
    ///     单例模板
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class Singleton<T> where T : Singleton<T>
    {
        protected static T MInstance;

        public static T Instance
        {
            get
            {
                if (MInstance == null)
                {
                    // 先获取所有非 public 的构造方法
                    var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);

                    // 从 ctors 中获取无参的构造方法
                    var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);

                    if (ctor == null) throw new Exception("Non-public ctor() not found!");

                    // 调用构造方法
                    MInstance = ctor.Invoke(null) as T;
                }

                return MInstance;
            }
        }
    }
}